﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Windows.Controls.GridView;

namespace Sunny.Controls
{
	public class RowNumberGridViewColumn : Telerik.Windows.Controls.GridViewColumn
	{
		public override System.Windows.FrameworkElement CreateCellElement(GridViewCell cell, object dataItem)
		{
			//var numberPresenter = cell.Content as RowNumberPresenter;
			//if (numberPresenter == null)
			//	numberPresenter = new RowNumberPresenter(this.DataControl, dataItem);
			return new RowNumberPresenter(this.DataControl, dataItem);
		}
	}

	public class RowNumberPresenter : System.Windows.Controls.TextBlock
	{
		private Telerik.Windows.Controls.GridView.GridViewDataControl _parentControl;
		public Telerik.Windows.Controls.GridView.GridViewDataControl ParentControl
		{
			get { return this._parentControl; }
			private set
			{
				if (this._parentControl != null)
					this._parentControl.Items.CollectionChanged -= new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Items_CollectionChanged);
				this._parentControl = value;
				if (this._parentControl != null)
					this._parentControl.Items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Items_CollectionChanged);
			}
		}

		public RowNumberPresenter(Telerik.Windows.Controls.GridView.GridViewDataControl parentControl, object dataItem)
			: base()
		{
			ParentControl = parentControl;
			SetText(dataItem);
		}

		private void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
		{
			SetText(this.DataContext);
		}

		private void SetText(object dataItem)
		{
			// in case of grouping, this code is used to display the row number based on the number of items in the grouping
			if (this.ParentControl.IsGrouping)
			{
				var group = this.ParentControl.FindGroupByItem(dataItem);
				if (group != null)
				{
					var items = group.Items as System.Collections.ObjectModel.ReadOnlyObservableCollection<object>;
					if (items != null)
						this.Text = (items.IndexOf(dataItem) + 1).ToString();
				}
			}
			if (string.IsNullOrEmpty(this.Text))
				this.Text = (this.ParentControl.Items.IndexOf(dataItem) + 1).ToString();
		}
	}
}